import React, { useState, useEffect, useRef } from 'react';
import './SearchBar.css'; 
import { useNavigate } from 'react-router-dom';
import { ReactComponent as SearchIcon } from '../assets/icons/search.svg';
import { ReactComponent as TargetIcon } from '../assets/icons/target.svg';
import { ReactComponent as ArticleIcon } from '../assets/icons/article.svg';
import { ReactComponent as UserIcon } from '../assets/icons/user.svg';
import defaultAvatar from '../assets/images/默认头像.jpg';
import { searchTopic, searchUser, searchPostBytime } from '../api/userApi'; // 导入接口

const SearchBar = () => {
  const [query, setQuery] = useState('');
  const [results, setResults] = useState({ topics: [], users: [], posts: [] });
  const [loading, setLoading] = useState(false);
  const [showResults, setShowResults] = useState(false);
  const navigate = useNavigate();
  const searchBoxRef = useRef(null);
  const searchResultsRef = useRef(null);
  const [userId, setUserId] = useState(null);

  useEffect(() => {
    const storedUserId = localStorage.getItem('userId');
    if (storedUserId) {
      setUserId(storedUserId);
      console.log(userId);
    }
  }, []);

  const fetchSearchResults = async (query) => {
    try {
      console.log(query,userId);
      const topicsResponse = await searchTopic(query,userId); 
      const usersResponse = await searchUser(query,userId);
      const postsResponse = await searchPostBytime(query,userId);
      console.log(topicsResponse);
      console.log(usersResponse);
      console.log(postsResponse);
      return {
        topics: topicsResponse || [],
        users: usersResponse|| [],
        posts: postsResponse || [],
      };
    } catch (error) {
      console.error('API 请求失败:', error);
      return { topics: [], users: [], posts: [] };
    }
  };

  const handleInputChange = (e) => {
    const input = e.target.value;
    setQuery(input);
    if (input) {
      setLoading(true);
      fetchSearchResults(input).then((data) => {
        setResults(data);
        setLoading(false);
        setShowResults(true);
      }).catch(() => {
        setLoading(false);
        setShowResults(false);
      });
    } else {
      setResults({ topics: [], users: [], posts: [] });
      setShowResults(false);
    }
  };

  const handleSearch = (e) => {
    e.preventDefault();
    if (query.trim()) {
      navigate(`/search?query=${encodeURIComponent(query)}`);
    }
  };

  const handleClickOutside = (e) => {
    if (
      searchBoxRef.current && !searchBoxRef.current.contains(e.target) &&
      searchResultsRef.current && !searchResultsRef.current.contains(e.target)
    ) {
      setShowResults(false);
    }
  };

  useEffect(() => {
    document.addEventListener("mousedown", handleClickOutside);
    return () => {
      document.removeEventListener("mousedown", handleClickOutside);
    };
  }, []);

   // 格式化时间
   const formatDate = (dateString) => {
    const options = { year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', hour12: false };
    const date = new Date(dateString);
    return date.toLocaleString('zh-CN', options).replace(/\//g, '-'); // 将 / 替换为 - 以符合中文日期格式
  };
  
  return (
    <div className="search-container">
      <form onSubmit={handleSearch} className="search-bar" ref={searchBoxRef}>
        <input 
          type="text" 
          placeholder="搜索..."
          value={query}
          onChange={handleInputChange}
          className="search-input"
          onFocus={() => { if (query) setShowResults(true); }}
        />
        <button type="submit" className="search-button">
          <SearchIcon className="search-icon" onClick={()=>navigate(`/search?query=${encodeURIComponent(query)}`)}/>
        </button>
      </form>

      {query && showResults && (
        <div className="search-results-container" ref={searchResultsRef}>
          <div className="search-results">
            <div className="search-column">
              <h4 style={{ display: 'flex', alignItems: 'center' }}>
                <TargetIcon className='search-column-icon' />
                相关话题
              </h4>
              {loading ? (
                <p>加载中...</p>
              ) : results.topics.length === 0 ? (
                <p>未找到相关话题</p>
              ) : (
                <ul>
                  {results.topics.map((topic) => (
                    <li 
                    key={topic.interestId} 
                    style={{ display: 'flex', marginBottom: '10px' }} 
                    onClick={() => navigate(`/topic/${topic.interestId}`)}
                    >
                      <span style={{ marginRight: '3px' }}>#</span>
                      {topic.name}
                    </li>
                  ))}
                </ul>
              )}
            </div>

            <div className="search-column">
              <h4 style={{ display: 'flex', alignItems: 'center' }}>
                <UserIcon className='search-column-icon' />
                相关用户
              </h4>
              {loading ? (
                <p>加载中...</p>
              ) : results.users.length === 0 ? (
                <p>未找到相关用户</p>
              ) : (
                <ul>
                  {results.users.map((user) => (
                    <li key={user.id} style={{ display: 'flex', marginBottom: '10px' }} onClick={() => navigate(`/personal/${user.userId}`)}>
                      <div style={{ display: 'flex', alignItems: 'center' }}>
                        <img 
                          src={'http://localhost:8080/'+user.image} 
                          alt="用户头像" 
                          className="user-avatar" 
                          style={{ borderRadius: '50%', width: '40px', height: '40px', marginRight: '8px' }} 
                        />                      

                        <div>
                          <span>{user.account}</span>
                          <br />
                          <span style={{ fontSize: '12px', color: '#888' }}>ID: {user.userId}</span>
                        </div>
                      </div>
                    </li>
                  ))}
                </ul>
              )}
            </div>

            <div className="search-column">
              <h4 style={{ display: 'flex', alignItems: 'center' }}>
                <ArticleIcon className='search-column-icon' />
                相关帖子
              </h4>
              {loading ? (
                <p>加载中...</p>
              ) : results.posts.length === 0 ? (
                <p>未找到相关帖子</p>
              ) : (
                <ul>
                  {results.posts.map((post) => (
                    <li key={post.blogId} style={{ display: 'flex', alignItems: 'center', marginBottom: '10px' }} onClick={() => navigate(`/post/${post.blogId}`)}>
                      <img src={'http://localhost:8080/'+post.blogImage} style={{ background: '#eee', width: '40px', height: '40px', marginRight: '8px' }}/>
                      <div style={{ flexGrow: 1 }}>
                        {post.description}
                        <br />
                        <span style={{ fontSize: '12px', color: '#888' }}>{formatDate(post.updateTime)}</span>
                      </div>
                    </li>
                  ))}
                </ul>
              )}
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default SearchBar;
